package team.xyg.cdtu2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import team.xyg.cdtu2.entity.Visit;
import team.xyg.cdtu2.service.VisitService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author liuyufeng
 * @Date 2022/6/23 0023 9:59
 * @Version 1.0
 */
@Component
public class IpInterceptor implements HandlerInterceptor {

    @Autowired
    private VisitService visitService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.拦截请求（只要访问当前网站，就拦截）
         * URL   http://localhost:8080/proviceofchina
         * URI   /proviceofchina
         * 2.获取ip
         * 3.判断数据
         */
        String requestURI = request.getRequestURI();
        String ip = null;
        if(requestURI.contains("index")){
            String remoteAddr = request.getRemoteAddr();
            if(remoteAddr.equals("0:0:0:0:0:0:0:1")){
                ip = "127.0.0.1";
            }else {
                ip = remoteAddr;
            }
            Visit visit = visitService.queryByIp(ip);
            if (visit == null){
                Visit visit1 = new Visit();
                visit1.setCount(1);
                visit1.setIp(ip);
                visitService.insert(visit1);
            }else{
                visit.setCount(visit.getCount() + 1);
                visitService.update(visit);
            }

        }

        return true;
    }


}
